package com.example.houseitemmanagebackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.houseitemmanagebackend.entity.UserLocation;
import com.example.houseitemmanagebackend.mapper.UserLocationMapper;
import com.example.houseitemmanagebackend.service.UserLocationService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户-位置关系服务实现类
 */
@Service
public class UserLocationServiceImpl extends ServiceImpl<UserLocationMapper, UserLocation>
        implements UserLocationService {

    @Override
    @Transactional
    public boolean addUserToLocation(Integer userId, Integer locationId, Integer roleType) {
        // 检查是否已存在关系
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getLocationId, locationId);
        UserLocation existingRelation = getOne(queryWrapper);

        if (existingRelation != null) {
            // 如果已存在关系，则更新角色类型
            existingRelation.setRoleType(roleType);
            existingRelation.setUpdatedAt(LocalDateTime.now());
            return updateById(existingRelation);
        } else {
            // 创建新的关系
            UserLocation userLocation = new UserLocation();
            userLocation.setUserId(userId);
            userLocation.setLocationId(locationId);
            userLocation.setRoleType(roleType);
            userLocation.setCreatedAt(LocalDateTime.now());
            userLocation.setUpdatedAt(LocalDateTime.now());
            return save(userLocation);
        }
    }

    @Override
    @Transactional
    public boolean updateUserLocationRole(Integer userId, Integer locationId, Integer roleType) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getLocationId, locationId);

        UserLocation userLocation = getOne(queryWrapper);
        if (userLocation == null) {
            return false;
        }

        userLocation.setRoleType(roleType);
        userLocation.setUpdatedAt(LocalDateTime.now());
        return updateById(userLocation);
    }

    @Override
    public List<Integer> getUsersByLocationId(Integer locationId) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getLocationId, locationId);

        return list(queryWrapper).stream()
                .map(UserLocation::getUserId)
                .collect(Collectors.toList());
    }

    @Override
    public List<Integer> getLocationsByUserId(Integer userId) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getUserId, userId);

        return list(queryWrapper).stream()
                .map(UserLocation::getLocationId)
                .collect(Collectors.toList());
    }

    @Override
    public boolean isLocationAdmin(Integer userId, Integer locationId) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getLocationId, locationId)
                .eq(UserLocation::getRoleType, 1) // 1表示管理员
                .or()
                .eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getLocationId, locationId)
                .eq(UserLocation::getRoleType, 2); // 2表示管理者

        return count(queryWrapper) > 0;
    }

    @Override
    public Integer getUserRoleTypeInLocation(Integer userId, Integer locationId) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getLocationId, locationId);

        UserLocation userLocation = getOne(queryWrapper);
        return userLocation != null ? userLocation.getRoleType() : null;
    }

    @Override
    @Transactional
    public boolean removeUserFromLocation(Integer userId, Integer locationId) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getUserId, userId)
                .eq(UserLocation::getLocationId, locationId);

        return remove(queryWrapper);
    }

    @Override
    public List<UserLocation> getUserLocationsByLocationId(Integer locationId) {
        LambdaQueryWrapper<UserLocation> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserLocation::getLocationId, locationId);
        return list(queryWrapper);
    }
}